<?php


/**
* Note
*/
class Note
{

  private $notes;

  function __construct( $config = array() )
  {
    foreach( $config as $key => $value )
      $this->{$key} = property_exists( get_class($this), $key) ? $value : null;  
  }

  /**
   * 
   * [getList description]
   * @param  [type] $fileName [description]
   * @return array Retourne un array contenant les informations des notes
   */
  private function getList($filePath)
  {
    $document = new DOMDocument;
    $document->load($filePath);
 
    $bieresDom = $document->getElementsByTagName('biere');

    // Tableau associatif
    // clé : idBiere
    // valeur : array des notes de la biere
    $liste = array();
    foreach( $bieresDom as $biereDom )
    {
      $notes = array();
      $notesDom = $biereDom->getElementsByTagName('note');
      foreach ($notesDom as $key => $noteDom) {
        array_push($notes, $noteDom->nodeValue);
      }
      $liste[$biereDom->getAttribute('id')] = $notes;
    }

    return $liste;
  }

  function save( $filePath )
  {
    $xml = new DOMDocument( "1.0", "UTF-8" );
    $xml->preserveWhiteSpace = false;
    $xml->formatOutput = true;


    $bieresDom = $xml->createElement( "bieres" );

    foreach ($this->getNotes() as $idBiere => $notes) {
      $biereDom = $xml->createElement( "biere" );
      $biereDom->setAttribute('id', $idBiere);

      $notesDom = $xml->createElement( "notes" );

      foreach ($notes as $note) {
        $noteDom = $xml->createElement( "note" );
        $noteDom->nodeValue = $note;
        $notesDom->appendChild($noteDom);
      }

      $biereDom->appendChild($notesDom);
      $bieresDom->appendChild($biereDom);
    }

    $xml->appendChild($bieresDom);

    $xml->save($filePath);
  }


  function addNote($idBiere, $note)
  {
    $liste = $this->getNotes();
    if(isset($liste[$idBiere]) && is_array($liste[$idBiere]))
      array_push($liste[$idBiere], $note);
    else
      $liste[$idBiere] = array($note);
    $this->notes = $liste;
  }

  function getNotes()
  {
    if(!isset($this->notes))
      $this->notes = $this->getList(Config::$urlNotes);
    return $this->notes;
  }


  /**
   * Retourne l'objet si l'élément $attribut == $valeur est présent dans $liste
   * Retourne null si l'objet n'est pas présent
   * @param  [type] $listeDegres [description]
   * @param  [type] $attribute   [description]
   * @param  [type] $value       [description]
   * @return [type]              [description]
   */
  static function getByAttribute( $liste, $attribut, $valeur)
  {
    foreach ($liste as $key => $degre) {
      if($degre->get($attribut) == $valeur)
        return $degre;
    }
    return null;
  }

  public function get( $key )
  {
    if ( property_exists( get_class($this), $key ) )
      return $this->{$key};
    else
      return null;
  }
  public function __set( $key, $value )
  {
    if ( property_exists( get_class($this), $key ) )
      $this->{$key} = $value;
  }
}

?>